import logging, sys, datetime, pytz, os, yaml
from yaml import Loader
from getopt import getopt
import get_article
import push_msg

main_version = '1.1.1'


def load_config(path: str):
    '''加载配置文件'''
    if path:
        with open(path, 'r', encoding='utf-8') as fp:
            return yaml.load(fp.read(), Loader=Loader)
    else:
        path = os.path.abspath(__file__)
        path = os.path.dirname(path) + '/config.yml'
        if os.path.exists(path):
            with open(path, 'r', encoding='utf-8') as fp:
                return yaml.load(fp.read(), Loader=Loader)
        raise RuntimeError('未找到配置文件')


def init_log(log_file: str, log_console: bool, log_timezone: str):
    '''初始化日志参数'''
    logger_raw = logging.getLogger()
    logger_raw.setLevel(logging.INFO)
    formatter = logging.Formatter("[%(asctime)s] [%(levelname)s]: %(message)s",
                                  "%Y-%m-%d %H:%M:%S")
    tz = pytz.timezone(log_timezone)
    formatter.converter = lambda x: datetime.datetime.now(tz).timetuple()
    if log_file:
        try:
            log_url = os.path.abspath(__file__)
            log_file = os.path.dirname(log_url) + '/' + log_file
            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setFormatter(formatter)
            logger_raw.addHandler(file_handler)
        except:
            ...
    if log_console:
        console_handler = logging.StreamHandler(stream=sys.stdout)
        console_handler.setFormatter(formatter)
        logger_raw.addHandler(console_handler)
    return True


def init_message(configData: dict):
    '''初始化消息推送'''
    try:
        init_log(configData["log_file"], configData["log_console"],
                 configData["log_timezone"])
        #if configData["webhook"]["enable"]:
        #webhook.set(configData["webhook"])
    except Exception as e:
        print(f'初始化消息推送异常，原因为{str(e)}，退出程序')
        sys.exit(1)


def start(configData: dict):
    '''开始任务'''
    config_version = configData.get('version', '0.0.0')
    if config_version == main_version:
        logging.info(f'当前程序版本为v{main_version},配置文件版本为v{config_version}')
    else:
        logging.warning(
            f'当前程序版本为v{main_version},配置文件版本为v{config_version},版本不匹配可能带来运行问题')
        #webhook.addMsg(f'当前配置版本不匹配，请尽快更新\n\n')
    for query in configData["query"]:
        if (query):
            if (configData['qq_push']['url']
                    and configData['qq_push']['verifyKey']
                    and configData['qq_push']['qq']
                    and configData['qq_push']['target']):
                run_user_tasks(configData["http_header"], query,
                               configData['qq_push'])
            else:
                logging.warning('QQ推送参数不全，请检查配置文件')
                #webhook.addMsg('QQ推送参数不全，请检查配置文件')
        else:
            logging.warning('查询条件为空，请检查配置文件')
            #webhook.addMsg('查询条件为空，请检查配置文件')
    #webhook.send()


def run_user_tasks(
        http_header: str,  #请求头
        query: str,  #查询条件
        qq_push: dict  #QQ推送
):
    try:
        get_article.init_data(query)  #初始化数据
        sougou_cookie, weixin_url = get_article.get_init_url(
            http_header)  #获取初始url
        weixin_real_url = get_article.get_real_url(weixin_url, sougou_cookie,
                                                   http_header)  #获取真实url
        weixin_article = get_article.get_article_data(weixin_real_url,
                                                      http_header)  #获取文章
        push_msg.push_msg(weixin_article, qq_push['url'], qq_push['header'],
                          qq_push['verifyKey'], qq_push['qq'],
                          qq_push['target'], qq_push['delay_time'])  #推送文章
        #sendmsg.send_msg_task()
    except Exception as e:
        logging.warning(
            f'任务异常, 原因为{str(e)}，位置{str(e.__traceback__.tb_lineno)}')


def main(**kwargs):
    try:
        configData = load_config(kwargs.get("config", None))
    except Exception as e:
        print(f'配置加载异常，原因为{str(e)}，退出程序')
        sys.exit(1)

    if 'log' in kwargs:
        configData["log_file"] = kwargs["log"]

    init_message(configData)  #初始化消息推送
    start(configData)  #启动任务


if __name__ == "__main__":
    kwargs = {}
    opts, args = getopt(sys.argv[1:], "hvc:l:", ["configfile=", "logfile="])
    for opt, arg in opts:
        if opt in ('-c', '--configfile'):
            kwargs["config"] = arg
        elif opt in ('-l', '--logfile'):
            kwargs["log"] = arg
    main(**kwargs)